#+_+ coding:utf-8 +_+

import json
import tornado.web
from base import BaseHdl
from storage import news
import auth
from common import buffer
import storage

COUNT = "10"

class TopNewsHdl(BaseHdl):
    def get(self):
        uid   = self.get_argument("uid","0")
        signature = self.get_argument("signature","")
        index = self.get_argument("index","0")
        count = self.get_argument("count",COUNT)
        
        rst = auth.IsValiedUID(uid)
        if not rst:
            rep = self.uidError()
        else:
            ticket = storage.uid.UID.GetTicket(uid)
            rst = auth.CheckSignature(signature,uid,index,count,ticket)
            if not rst :
                rep = self.signatureError()
            else:
                rep = self.topNews(index,count)
        self.write(rep)


    def topNews(self,index,count):
        newsList = list()
        newsIDs = news.GetTopNewsIDs(index,count)
        lastID = -1
        for id in newsIDs:
            if lastID < 0 : 
                lastID =id
            elif lastID < id:
                lastID = id
            newsItem = news.GetNews(id)
            newsList.append(dict(id=newsItem["id"],author=newsItem["author"],title=newsItem["title"],time=newsItem["time"],star=newsItem["star"]))
            
            
        count = len(newsList)
        msg = dict(last_id=lastID,count=count,news=newsList)
        rep = dict(rst="SUCCESS",msg=msg)
        return buffer.JsonEncode(rep)

